package com.yoke.controller.images;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.QiNiuFile;
import com.yoke.common.base.NginxBaseControl;
import com.yoke.controller.digging.DiggingControl;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.FileUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * Created by jiangzeyin on 2017/6/22.
 */
@Controller
@RequestMapping("images")
public class ImagesControl extends NginxBaseControl {

    @RequestMapping(value = "index.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String index() {
        return "images/index";
    }

    /**
     * 上传接口
     *
     * @return
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String upload() {
        if (!(request instanceof MultipartHttpServletRequest)) {
            return JsonMessage.getString(400, "这不是上传文件操作");
        }
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileHashMap = multipartHttpServletRequest.getFileMap();
        if (fileHashMap == null || fileHashMap.size() < 1)
            return JsonMessage.getString(400, "请选择要上传的文件");
        String doMain;
        try {
            doMain = DiggingControl.getDoMain();
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("上传解析域名异常", e);
            return JsonMessage.getString(401, "上传失败，系统异常");
        }
        Set<Map.Entry<String, MultipartFile>> entries = fileHashMap.entrySet();
        File file = new File(String.format("%s/temp/upload/img/%s", getBootPath(), userName));
        FileUtil.deleteDir(file);
        String quality = multipartHttpServletRequest.getParameter("quality");
        String type = multipartHttpServletRequest.getParameter("type");
        boolean isFile = "file".equals(type);
        float quality_ = StringUtil.parseFloat(quality);
        if (quality_ == 0.0F) {
            quality_ = 0.7f;
        } else if (quality_ != 100F && (quality_ <= 0.0F || quality_ >= 1.0F)) {
            quality_ = 0.7f;
        }
        JSONArray jsonArray = new JSONArray();
        for (Map.Entry<String, MultipartFile> entry : entries) {
            String key = entry.getKey();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", key);
            jsonArray.add(jsonObject);
            MultipartFile multipartFile = entry.getValue();
            jsonObject.put("name", multipartFile.getOriginalFilename());
            if (multipartFile.isEmpty()) {
                jsonObject.put("msg", "存在空文件");
                continue;
            }

            boolean flag = false;
            InputStream inputStream_;
            try {
                InputStream inputStream = multipartFile.getInputStream();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) > -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                byteArrayOutputStream.flush();
                byteArrayOutputStream.close();
                // 打开一个新的输入流
                InputStream is1 = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                inputStream_ = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                if (!isFile) {
                    // 判断是否为图片
                    flag = isImage(is1);
                }
            } catch (IOException e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("上传异常", e);
                jsonObject.put("msg", "图片解析失败");
                continue;
            }
            if (!isFile && !flag) {
                jsonObject.put("msg", "选择的文件不是图片");
                continue;
            }
            String fileName = String.format("%s/%s", file.getPath(), UUID.randomUUID());
            try {
                flag = FileUtil.writeInputStream(inputStream_, fileName);
            } catch (IOException e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("写文件失败", e);
                jsonObject.put("msg", "上传文件失败");
                continue;
            }
            if (!flag) {
                jsonObject.put("msg", "上传文件失败:-1");
                continue;
            }
            String md5;
            try {
                if (isFile)
                    md5 = QiNiuFile.doUploadFile(fileName, 100.0f);
                else
                    md5 = QiNiuFile.doUploadFile(fileName, quality_);
            } catch (Exception e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("上传失败", e);
                jsonObject.put("msg", e.getMessage());
                continue;
            }
            jsonObject.put("url", FileUtil.ClearPath(String.format("%s/%s", doMain, md5)));
            SystemLog.LOG(LogType.CONTROL).info(String.format("%s 上传 %s", userName, md5));
        }
        return JsonMessage.getString(200, "上传成功", jsonArray);
    }

    public static boolean isImage(InputStream inputStream) {
        if (inputStream == null) {
            return false;
        }
        Image img;
        try {
            img = ImageIO.read(inputStream);
            return !(img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0);
        } catch (Exception e) {
            return false;
        }
    }


    public static String getImageType(File srcFilePath) {
        FileInputStream imgFile;
        byte[] b = new byte[10];
        int len;
        try {
            imgFile = new FileInputStream(srcFilePath);
            len = imgFile.read(b);
            imgFile.close();
        } catch (Exception e) {
            return null;
        }
        if (len != b.length) {
            return null;
        }
        byte b0 = b[0];
        byte b1 = b[1];
        byte b2 = b[2];
        byte b3 = b[3];
        byte b6 = b[6];
        byte b7 = b[7];
        byte b8 = b[8];
        byte b9 = b[9];
        if (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F') {
            return "gif";
        }
        if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') {
            return "png";
        }
        if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F') {
            return "jpg";
        }
        if (b6 == (byte) 'E' && b7 == (byte) 'x' && b8 == (byte) 'i' && b9 == (byte) 'f') {
            return "exif";
        }
        return null;
    }
}
